﻿
using Bootstrap5.Abstractions;

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Rendering;

namespace Bootstrap5;

/// <summary>
/// Represents a control that provides a menu of options as &lt;select> element.
/// </summary>
[HtmlTag("select")]
[CssClass("form-select")]
public class FormSelect : FormControlBase<string>,IHasChildContent
{
    /// <summary>
    /// Indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. 
    /// </summary>
    [Parameter][HtmlProperty("multiple")]public bool Multiple { get; set; }
    /// <summary>
    /// When <see cref="Multiple"/> is specified, this attribute represents the number of rows in the list that should be visible at one time. 
    /// </summary>
    [Parameter] [HtmlProperty("size")] public int? MultipleSize { get; set; }
    /// <summary>
    /// Size of control.
    /// </summary>
    [Parameter] [CssClass("form-select-")] public Size? Size { get; set; }
    /// <summary>
    /// Gets or sets the child content to be rendering inside the select element.
    /// </summary>
    [Parameter] public RenderFragment ChildContent { get; set; }

    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        if (CascadedFloating is not null)
        {
            BuildSelect(builder);
            BuildLabel(builder);
        }
        else
        {
            BuildLabel(builder);
            BuildSelect(builder);
        }
    }

    private void BuildSelect(RenderTreeBuilder builder)
    {
        builder.OpenRegion(100);
        builder.OpenElement(0, GetHtmlTagName());
        builder.AddAttribute(2, "value", CurrentValueAsString);
        builder.AddAttribute(3, "name", FieldIdentifier.FieldName);
        builder.AddAttribute(4, "onchange", EventCallback.Factory.CreateBinder(this, __value => CurrentValue = __value, CurrentValue));
        BuildCommonAttributes(builder);
        BuildChildContent(builder);
        builder.CloseElement();
        builder.CloseRegion();
    }
}
